package cn.edu.ldu.http;


import cn.edu.ldu.views.modules.controller.UserController;
import cn.edu.ldu.util.L;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.configurationprocessor.json.JSONTokener;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class rqtUtils {

    public static JSONObject httpclientGet(StringBuffer getMappingUrl, String token) throws Exception {

        // 创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建GET请求（在构造器中传入URL字符串即可）
        HttpGet get;
        if(token != null)
            get = new HttpGet(withToken(getMappingUrl, token));
        else
            get = new HttpGet(getMappingUrl.toString());

        // 调用HttpClient对象的execute方法获得响应
        CloseableHttpResponse response = client.execute(get);

        // 调用HttpResponse对象的getEntity方法得到响应实体
        HttpEntity httpEntity = response.getEntity();

        // 使用EntityUtils工具类得到响应的字符串表示
        String result = EntityUtils.toString(httpEntity,"utf-8");

        L.OK("==> " + get, rqtUtils.class);
        L.OK("<== " + result, rqtUtils.class);

        try {
            client.close();
            response.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return JSON.parseObject(result);
    }


    public static String httpclientPost(StringBuffer postMappingUrl, String jsonString, String token) throws Exception {

        // 创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();

        // 创建POST请求
        HttpPost post;
        if(token != null)
            post = new HttpPost(withToken(postMappingUrl, token));
        else
            post = new HttpPost(postMappingUrl.toString());
        //设置访问超时
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
        post.setConfig(requestConfig);

        StringEntity entity = new StringEntity(jsonString, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        // 向POST请求中添加消息实体
        post.setEntity(entity);
        CloseableHttpResponse response = null;
        // 得到响应并转化成字符串
        try {

            response = client.execute(post);
            L.OK("==> " + post, rqtUtils.class);

            int state = response.getStatusLine().getStatusCode();
            if(state == HttpStatus.SC_OK){

                HttpEntity httpEntity = response.getEntity();
                String result = EntityUtils.toString(httpEntity,"utf-8");
                L.OK("<== " + JSON.parseObject(result), rqtUtils.class);
                return result;
            }

        }finally {
            if(response != null){
                try {
                    response.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            try {
                client.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return null;
    }


    private static String withToken(StringBuffer sb, String tokens){
        if(sb.lastIndexOf("?") >= 0){
            sb.append("&token=").append(tokens);
        }else {
            sb.append("?token=").append(tokens);
        }
        return sb.toString();
    }

}
